package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.User;

public class QuerySingleUserResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.QuerySingleShowSubResultPaser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {
		
		ArrayList<DataElement> res = new ArrayList<DataElement>();

		NodeList news =  doc.getElementsByTagName("user"); 
		
		if(news.getLength() < 1 
				|| !news.item(0).hasChildNodes()){
			return res;
		}
		
		Node node = news.item(0);
						
		DataElement el = parseNode(node);
		if(el != null){
			res.add(el);
		}
				
		return res;
	}

	private DataElement parseNode(Node n) {
		
		Element e = (Element)n;
		
		int id = -1;
		id = W3CParsingHandler.parseIntValue(e, "id");
		if(id == -1)
			return null;
		
		User el = new User(id);
		
		el.setName(DomHandler.getValue(e, "name"));
		el.setUsername(DomHandler.getValue(e, "username"));
		el.setEmail(DomHandler.getValue(e, "email"));
		el.setLastVisit(W3CParsingHandler.parseW3CDateValue(e, "last_visit"));
		el.setAuthcode(DomHandler.getValue(e, "authcode"));
		el.setHasMyItasa(W3CParsingHandler.parseBooleanValue(e, "has_myitasa"));
		el.setRegisterDate(W3CParsingHandler.parseW3CDateValue(e, "register_date"));
		el.setGender(DomHandler.getValue(e, "gender"));
		el.setBirthdate(W3CParsingHandler.parseSimpleDateValue(e, "birthdate"));
		el.setLocation(DomHandler.getValue(e, "location"));
		el.setWebsiteUrl(W3CParsingHandler.parseURLValue(e, "website_url"));
		el.setUnreadMsgs(W3CParsingHandler.parseIntValue(e, "unread_messages"));
		el.setAvatar(W3CParsingHandler.parseURLValue(e, "avatar"));
		
		return el;
	}


	
}
